package com.shapawan.tourism.controller;

import com.shapawan.tourism.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传控制器
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = {"http://localhost:5173", "http://localhost:8080"}, allowedHeaders = "*",
        methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT},
        allowCredentials = "false")
@Slf4j
public class FileController {

    @Value("${file.upload-path}")
    private String uploadPath;

    @Value("${file.access-url}")
    private String accessUrl;

    @ApiOperation("上传文件")
    @PostMapping
    public Result<Map<String, String>> uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) {
        log.info("收到文件上传请求，文件是否为null: {}", file == null);
        if (file == null) {
            log.info("尝试从请求中获取文件");
            return Result.failed("未找到上传文件，请确保使用'file'作为参数名");
        }

        log.info("收到文件: {}, 大小: {}字节", file.getOriginalFilename(), file.getSize());

        // 检查文件是否为空
        if (file.isEmpty()) {
            return Result.failed("上传的文件为空");
        }

        try {
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                log.info("创建上传目录: {}", uploadPath);
                uploadDir.mkdirs();
            }

            // 创建日期子目录
            String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File dirPath = new File(uploadPath + dateDir);
            if (!dirPath.exists()) {
                log.info("创建日期目录: {}", dirPath.getAbsolutePath());
                dirPath.mkdirs();
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString().replaceAll("-", "") + extension;
            String relativePath = dateDir + "/" + newFilename;
            String fullPath = uploadPath + relativePath;

            log.info("保存文件到: {}", fullPath);

            // 保存文件
            File dest = new File(fullPath);
            file.transferTo(dest);

            // 返回访问URL
            Map<String, String> result = new HashMap<>();
            result.put("url", accessUrl + relativePath);
            result.put("filename", originalFilename);

            log.info("文件上传成功：{}", result);
            return Result.success(result);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.failed("文件上传失败：" + e.getMessage());
        }
    }

    @ApiOperation("上传图片")
    @PostMapping("/image")
    public Result<Map<String, String>> uploadImage(@RequestParam(value = "file", required = false) MultipartFile file) {
        log.info("收到图片上传请求，文件是否为null: {}", file == null);
        if (file == null) {
            log.info("尝试从请求中获取图片文件");
            return Result.failed("未找到上传图片，请确保使用'file'作为参数名");
        }

        log.info("收到图片: {}, 大小: {}字节", file.getOriginalFilename(), file.getSize());

        // 检查文件是否为空
        if (file.isEmpty()) {
            return Result.failed("上传的图片为空");
        }

        // 验证是否为图片格式
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"};

        if (!Arrays.asList(allowedExtensions).contains(extension)) {
            log.warn("上传的文件不是支持的图片格式: {}", extension);
            return Result.failed("只支持上传jpg、jpeg、png、gif、bmp和webp格式的图片");
        }

        try {
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                log.info("创建上传目录: {}", uploadPath);
                uploadDir.mkdirs();
            }

            // 创建日期子目录，并添加images子目录专门存放图片
            String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String imageDir = "images/";
            File dirPath = new File(uploadPath + dateDir + "/" + imageDir);
            if (!dirPath.exists()) {
                log.info("创建图片目录: {}", dirPath.getAbsolutePath());
                dirPath.mkdirs();
            }

            // 生成唯一文件名
            String newFilename = UUID.randomUUID().toString().replaceAll("-", "") + extension;
            String relativePath = dateDir + "/" + imageDir + newFilename;
            String fullPath = uploadPath + relativePath;

            log.info("保存图片到: {}", fullPath);

            // 保存文件
            File dest = new File(fullPath);
            file.transferTo(dest);

            // 返回访问URL
            Map<String, String> result = new HashMap<>();
            result.put("url", accessUrl + relativePath);
            result.put("filename", originalFilename);

            // 添加额外图片信息
            result.put("type", "image");
            result.put("size", String.valueOf(file.getSize()));

            log.info("图片上传成功：{}", result);
            return Result.success(result);
        } catch (IOException e) {
            log.error("图片上传失败", e);
            return Result.failed("图片上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/test")
    public Result<String> test() {
        log.info("测试接口被调用");
        return Result.success("文件上传接口正常工作");
    }
} 